package core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import misc.Log;

public class Bridge {

	private static final class Holder extends ThreadLocal<Bridge> {
		@Override
		protected Bridge initialValue() {
			return new Bridge();
		}
	}

	private static final Holder holder = new Holder();
	
	private Socket sock = null;
	private PrintWriter out = null;
	private BufferedReader in = null;
	
	private Bridge() {}

	public static void init(String host, int port) {
		Bridge instance = holder.get();
		if (instance.sock == null) {
			try {
				instance.sock = new Socket(host, port);
				instance.out = new PrintWriter(instance.sock.getOutputStream(), true);
				instance.in = new BufferedReader(new InputStreamReader(instance.sock.getInputStream()));
			} catch (UnknownHostException e) {
				Log.fatal("Don't know about host: localhost.");
			} catch (IOException e) {
				Log.fatal("Couldn't get I/O for the connection to: localhost.");
			}
		}
	}

	public static synchronized String request(String cmd) {
		Bridge instance = holder.get();
		try {
			instance.out.println(cmd);
			return instance.in.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
}
